<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1000">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      v-loading="formLoading"
      :inline-message="true"
    >
      <!-- 关键修改：添加 key 属性确保表格正确渲染 -->
      <el-table :data="formData" :key="tableKey" class="-mt-10px">
        <el-table-column label="值">
           <template #default="{ row }">
          {{ row.value }}
        </template>
        </el-table-column>
        <el-table-column label="描述" min-width="100">
           <template #default="{ row }">
          {{ row.description }}
        </template>
        </el-table-column>
        <el-table-column label="是否启用" min-width="100">
         <template #default="{ row }">
          {{ row.isEnabled === true ? '启用' : '禁用' }}
        </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" sortable min-width="100">
           <template #default="{ row }">
          {{ row.sort }}
        </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="100">
           <template #default="{ row }">
          {{ formatCreateTime(row.createTime) }}
        </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="{ $index }">
            <el-button link type="danger" @click="handleRemove($index)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <!-- 添加弹窗底部操作按钮 -->
    <template #footer>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
      <el-button type="primary" @click="submitForm">确认</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { CommonStatusEnum } from '@/utils/constants'
import { StockApi, DictItemConfigVO } from '@/api/erp/stock/stock'
import dayjs from 'dayjs' 

defineOptions({ name: 'DictItemForm' })
const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
// 修复1：初始化 formData 为数组
const formData = ref<DictItemConfigVO[]>([])
const formState = reactive({ formData })

const tableKey = ref(0) // 用于强制刷新表格
const dictId = ref<number>()
const formRef = ref()

// 修复2：正确初始化表单规则
const formRules = reactive({
  value: [{ required: true, message: '字典项不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
})
const formatCreateTime = (timestamp: number) => {
  if (!timestamp) return '-' // 处理空值
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
}
const loadDictItems = async () => {
  if (!dictId.value) return;
  
  try {
    formLoading.value = true;
    const res = await StockApi.getSysDictItemPage({ dictId: dictId.value });
    formData.value = (res.list || []).map((item) => ({
      ...item,
      sort: item.sort ? Number(item.sort) : 0
    }));
    tableKey.value += 1; // 强制刷新表格
  } finally {
    formLoading.value = false;
  }
};
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = '字典项数据'
  formType.value = type
  dictId.value = id
  resetForm()
   if (id) {
    await loadDictItems(); // 修改为调用新封装的加载函数
  }
}

/** 删除行 */
const handleRemove = async (index: number) => {
  const item = formData.value[index];
   if (!item.id) {
      message.error('无效的数据项');
      return;
    }
   try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await StockApi.deleteSysDictItem(item.id)
    message.success(t('common.delSuccess'))
    await loadDictItems();
    // 刷新列表
  } catch {}
   
}

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm =  () => {
    dialogVisible.value = false
}

/** 重置表单 */
const resetForm = () => {
  // 修复6：重置为数组
  formData.value = []
  tableKey.value += 1
  formRef.value?.resetFields()
}

defineExpose({ open })
</script>
